package com.FengChaoSystem.servlet;

import com.FengChaoSystem.pojo.Coupon;
import com.FengChaoSystem.pojo.Order;
import com.FengChaoSystem.pojo.User;
import com.FengChaoSystem.service.CouponImpl;
import com.FengChaoSystem.service.CouponService.CouponService;
import com.FengChaoSystem.service.CourierImpl;
import com.FengChaoSystem.service.CourierService.CourierService;
import com.FengChaoSystem.service.UserImpl;
import com.FengChaoSystem.service.UserService.UserService;
import com.FengChaoSystem.untils.VCodeUtils;
import com.Mybatis.scripting.defaults.DefaultParameterHandler;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@WebServlet("/User/*")
public class UserServlet extends BaseServlet{
    private Logger logger = LoggerFactory.getLogger(UserServlet.class);
    private UserImpl service=new UserService();

    /**
     * 查找用户信息，用了redis作缓存
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int userId = (int) session.getAttribute("userId");
        Jedis jedis=new Jedis("127.0.0.1",6379);

        String cachedData = jedis.get("user:" + userId); // 假设缓存键是以"user:"为前缀，后跟用户ID

        if (cachedData != null) {
            // 如果缓存中存在数据，直接返回缓存数据
            logger.info("查询了userId为"+userId+"的信息：{}",cachedData);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(cachedData);
        } else {
            // 如果缓存中不存在数据，则从数据库中获取数据，并将其存入缓存
            User user = new User();
            user.setId(userId);
            User result = service.selectUserInfo(user);
            String jsonString = JSON.toJSONString(result);

            // 将数据存入缓存，设置过期时间，比如设定缓存时间为30分钟
            jedis.setex("user:" + userId, 1800, jsonString);

            // 返回数据给客户端
            logger.info("查询了userId为"+userId+"的信息：{}",jsonString);

            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
        }
        // 关闭Jedis连接
        jedis.close();
    }

    /**
     * 用于增加订单就是在寄件的时候用
     * @param request
     * @param response
     * @throws Exception
     */
    public void addOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int userId = (int) session.getAttribute("userId");
        String check = request.getParameter("check");

        User temp=new User();
        temp.setId(userId);
        User result=service.selectNowMoney(temp);
        if(result.getNowMoney() < 15 && (check == null||check.equals("false"))){
         response.getWriter().write("You are poor");
         return;
        }
        result.setId(userId);
        if(check == null||check.equals("false")){
        result.setNowMoney(result.getNowMoney()-15);}
        else{
            result.setNowMoney(result.getNowMoney()-5);
            CouponImpl tempService=new CouponService();
            Coupon coupon=new Coupon();
            coupon.setUserId(userId);
            List<Coupon> coupons = tempService.selectAllCanUseCoupon(coupon);
            coupon.setId(coupons.get(0).getId());
            coupon.setStatus(1);
            tempService.updateStatus(coupon);

        }
        service.updateNowMoney(result);
        BufferedReader reader = request.getReader();
        String param = reader.readLine();
        Order order= JSON.parseObject(param, Order.class);
        order.setFromUserId(userId);
        String onlyId = VCodeUtils.verifyCode(8);
        order.setOnlyId(onlyId);
        temp.setPhone(order.getReceivePhone());
        User user = service.selectUserInfoByReceivePhone(temp);
        if(user!=null)
        order.setToUserId(user.getId());
        else{
           order.setMax();
        }
        while (service.hasOnlyId(order)!=null){
            order.setOnlyId(VCodeUtils.verifyCode(8));
        }

        service.addOrder(order);

        response.getWriter().write("success");
    }

    /**
     * 用于修改用户信息
     * @param request
     * @param response
     * @throws Exception
     */
    public void updateInfoOfUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Jedis jedis=new Jedis("127.0.0.1",6379);
        HttpSession session = request.getSession();
        int userId = (int)session.getAttribute("userId");
        User target=new User();
        target.setId(userId);
        User oldUser = service.selectUserInfo(target);
        BufferedReader reader = request.getReader();
        String param = reader.readLine();
        User newUser= JSON.parseObject(param, User.class);
        if(oldUser.getIdentity()==0){
        newUser.setId(userId);
        service.updateInfoOfUser(newUser);
        Order order =new Order();
        order.setReceiveAddress(oldUser.getPhone());
        order.setReceivePhone(newUser.getPhone());
        System.out.println(order.toString());
        service.updateReceivePhone(order);
        session.removeAttribute("phone");
        session.setAttribute("phone",newUser.getPhone());
        }
        else{
            service.updateInfoOfUser(newUser);

        }
        response.getWriter().write("success");
        jedis.del("user:" + userId);
        jedis.close();
    }

    /**
     * 以下两个为充值请求
     * @param request
     * @param response
     * @throws Exception
     */

    public void addLittleMoney(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Jedis jedis=new Jedis("127.0.0.1",6379);
        HttpSession session = request.getSession();
        int userId =(int) session.getAttribute("userId");
        User user=new User();
        user.setId(userId);
        User result = service.selectNowMoney(user);
        int nowMoney = result.getNowMoney();
        user.setNowMoney(nowMoney+5);
        service.updateNowMoney(user);
        response.getWriter().write("success");
        jedis.del("user:" + userId);
        jedis.close();
    }
    public void addMuchMoney(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Jedis jedis=new Jedis("127.0.0.1",6379);
        HttpSession session = request.getSession();
        int userId =(int) session.getAttribute("userId");
        User user=new User();
        user.setId(userId);
        User result = service.selectNowMoney(user);
        int nowMoney = result.getNowMoney();
        user.setNowMoney(nowMoney+648);
        service.updateNowMoney(user);
        response.getWriter().write("success");
        jedis.del("user:" + userId);
        jedis.close();
    }

    /**
     * 用于获取当前聊天界面的用户名
     * @param request
     * @param response
     * @throws Exception
     */
    public void getUserName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int userId = (int) session.getAttribute("userId");
        User user=new User();
        user.setId(userId);
        User result = service.selectUserInfo(user);
        String jsonString = JSON.toJSONString(result);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    /**
     * 用于在聊天界面获取对方的名字
     * @param request
     * @param response
     * @throws Exception
     */
    public void getToUserName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String receivePhone = request.getParameter("receivePhone");
        if (receivePhone!=null) {
            System.out.println(receivePhone);
            User target=new User();
            target.setPhone(receivePhone);
            User result = service.selectUserInfoByReceivePhone(target);
            String jsonString = JSON.toJSONString(result);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
        }else {
            String id = request.getParameter("id");
            int userId=Integer.parseInt(id);
            User user=new User();
            user.setId(userId);
            User result = service.selectUserInfo(user);
            String jsonString = JSON.toJSONString(result);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
        }
    }

    }
